package com.zzzy.framework.dto;

import com.zzzy.common.util.ServletUtils;
import com.zzzy.framework.common.constant.AdminUserConstant;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Description: 登录用户身份权限
 *
 * @author fc
 * @date 2024/4/12
 */
@Data
public class LoginUser implements UserDetails {
    private static final long serialVersionUID = 1L;

    private Long id;
    /**
     * 登录名
     */
    private String username;

    private String password;
    /**
     * 真实姓名
     */
    private String nickName;
    /**
     * 手机号码
     */
    private String phoneNumber;
    /**
     * 用户邮箱
     */
    private String email;

    private String status;

    private Long deptId;

    private String token;

    /**
     * 数据权限
     */
    private DataPermissionDto dataPermissionDto;

    /**
     * 菜单权限集合
     */
    private Set<String> permissions;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public boolean isAdmin() {
        //id 为 1 为超级管理员
        return AdminUserConstant.ID.equals(id);
    }

    public boolean hasControllerPermission(String operate){
        HttpServletRequest request = ServletUtils.getRequest();
        String path = request.getRequestURI();
        String[] splitArr = path.replace(request.getContextPath(), "")
                .replaceAll("\\d", "").split("/");
        splitArr[splitArr.length - 1] = operate;
        String menuPermission = Arrays.stream(splitArr).filter(StringUtils::isNotBlank).collect(Collectors.joining(":"));
        return isAdmin() || permissions.contains(menuPermission);
    }
}
